<script setup>
import { ref, reactive, onMounted } from 'vue';
import * as echarts from 'echarts';

// 自然语言搜索相关状态和函数
const searchQuery = ref('');
const searchResults = ref([]);
const isSearching = ref(false);
const searchHistory = ref([
  '找出上个月销售额最高的产品',
  '哪个科室的患者满意度最低',
  '显示各科室患者数量变化趋势',
  '分析急诊科的高峰时段'
]);

// 模拟执行自然语言搜索
const performSearch = () => {
  if (!searchQuery.value.trim()) return;
  
  isSearching.value = true;
  // 将搜索记录添加到历史
  if (!searchHistory.value.includes(searchQuery.value)) {
    searchHistory.value.unshift(searchQuery.value);
    if (searchHistory.value.length > 5) {
      searchHistory.value.pop();
    }
  }
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 根据不同查询模拟不同结果
    if (searchQuery.value.includes('销售额') || searchQuery.value.includes('收入')) {
      searchResults.value = {
        type: 'sales',
        title: '销售额分析结果',
        chart: 'bar',
        data: {
          categories: ['心脏支架', '胰岛素泵', 'CT诊断', '核磁共振', '超声检查', '血液检测'],
          values: [125000, 98000, 87500, 76300, 65400, 54200]
        },
        insight: '心脏支架是上月销售额最高的产品，比第二名高出27.5%。医疗器械类产品整体表现优于诊断服务。'
      };
    } else if (searchQuery.value.includes('患者满意度')) {
      searchResults.value = {
        type: 'satisfaction',
        title: '患者满意度分析',
        chart: 'gauge',
        data: {
          departments: ['内科', '外科', '妇产科', '儿科', '眼科', '急诊科'],
          scores: [92, 88, 91, 95, 89, 82]
        },
        insight: '急诊科的患者满意度最低(82分)，主要原因是等待时间长和医生沟通不足。儿科满意度最高(95分)，主要优势在医患沟通和环境舒适度。'
      };
    } else if (searchQuery.value.includes('患者数量') || searchQuery.value.includes('趋势')) {
      searchResults.value = {
        type: 'trend',
        title: '患者数量趋势分析',
        chart: 'line',
        data: {
          months: ['1月', '2月', '3月', '4月', '5月', '6月'],
          departments: ['内科', '外科', '妇产科', '儿科', '眼科'],
          values: [
            [520, 532, 601, 634, 690, 720],
            [380, 420, 405, 488, 505, 510],
            [220, 210, 280, 360, 425, 390],
            [180, 175, 220, 278, 320, 352],
            [140, 120, 140, 172, 190, 210]
          ]
        },
        insight: '所有科室患者量整体呈上升趋势，内科增长率最高(38.5%)，妇产科在6月出现首次下滑(-8.2%)，可能与季节性因素有关。'
      };
    } else if (searchQuery.value.includes('高峰') || searchQuery.value.includes('急诊')) {
      searchResults.value = {
        type: 'peak',
        title: '急诊科接诊高峰分析',
        chart: 'heatmap',
        data: {
          hours: ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
          days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          values: [
            [3, 2, 2, 3, 12, 25, 18, 22, 26, 25, 18, 10],
            [4, 1, 2, 2, 15, 28, 20, 23, 24, 27, 17, 8],
            [2, 3, 1, 4, 14, 26, 22, 24, 25, 29, 15, 7],
            [5, 2, 3, 3, 13, 25, 21, 20, 28, 31, 20, 9],
            [6, 4, 2, 5, 15, 24, 19, 21, 27, 35, 28, 15],
            [12, 15, 18, 10, 8, 15, 18, 22, 30, 38, 42, 30],
            [15, 18, 12, 9, 7, 13, 16, 20, 25, 32, 35, 26]
          ]
        },
        insight: '周末晚间(20:00-22:00)是急诊高峰期，周六晚间平均接诊量达42人次/小时，比工作日同时段高53%。工作日早晨(08:00-10:00)是次高峰期，主要为急性症状患者。'
      };
    } else {
      searchResults.value = {
        type: 'generic',
        title: '查询结果',
        insight: '未能找到与您查询完全匹配的数据。请尝试使用更具体的关键词，如"销售额"、"患者满意度"、"趋势"等。'
      };
    }
    
    isSearching.value = false;
    
    // 初始化相应图表
    if (searchResults.value.chart) {
      setTimeout(() => {
        initChart(searchResults.value);
      }, 100);
    }
  }, 1500);
};

// 使用历史搜索
const useHistorySearch = (query) => {
  searchQuery.value = query;
  performSearch();
};

// 清除搜索结果
const clearSearch = () => {
  searchResults.value = [];
  searchQuery.value = '';
};

// 初始化图表
const initChart = (result) => {
  const chartDom = document.getElementById('resultChart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  let option = {};
  
  switch (result.chart) {
    case 'bar':
      option = {
        title: {
          text: result.title,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: result.data.categories,
          axisLabel: {
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: result.data.values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      };
      break;
    case 'gauge':
      option = {
        title: {
          text: result.title,
          left: 'center'
        },
        tooltip: {
          formatter: '{a} <br/>{b} : {c}%'
        },
        series: result.data.departments.map((dept, index) => ({
          name: '满意度',
          type: 'gauge',
          min: 0,
          max: 100,
          splitNumber: 10,
          radius: `${70 - index * 10}%`,
          axisLine: {
            lineStyle: {
              width: 8,
              color: [
                [0.7, '#fd666d'],
                [0.8, '#fdb36a'],
                [0.9, '#fdd56a'],
                [1, '#37c15b']
              ]
            }
          },
          pointer: {
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            distance: -30,
            length: 8,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          splitLine: {
            distance: -30,
            length: 30,
            lineStyle: {
              color: '#fff',
              width: 4
            }
          },
          axisLabel: {
            color: 'auto',
            distance: 40,
            fontSize: 12
          },
          detail: {
            valueAnimation: true,
            formatter: '{value}分',
            color: 'auto'
          },
          data: [{
            value: result.data.scores[index],
            name: dept
          }]
        })).slice(0, 3) // 只显示前三个部门的仪表盘
      };
      break;
    case 'line':
      option = {
        title: {
          text: result.title,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: result.data.departments,
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: result.data.months
        },
        yAxis: {
          type: 'value'
        },
        series: result.data.departments.map((dept, index) => ({
          name: dept,
          type: 'line',
          data: result.data.values[index],
          smooth: true
        }))
      };
      break;
    case 'heatmap':
      option = {
        title: {
          text: result.title,
          left: 'center'
        },
        tooltip: {
          position: 'top',
          formatter: function (params) {
            return `${params.name} ${result.data.hours[params.data[0]]}<br>接诊量: ${params.data[2]}`;
          }
        },
        grid: {
          height: '60%',
          top: '10%',
          left: '5%',
          right: '5%'
        },
        xAxis: {
          type: 'category',
          data: result.data.hours,
          splitArea: {
            show: true
          }
        },
        yAxis: {
          type: 'category',
          data: result.data.days,
          splitArea: {
            show: true
          }
        },
        visualMap: {
          min: 0,
          max: 45,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '5%',
          inRange: {
            color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
          }
        },
        series: [{
          name: '接诊量',
          type: 'heatmap',
          data: result.data.values.flatMap((row, i) => 
            row.map((val, j) => [j, i, val])
          ),
          label: {
            show: false
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      break;
  }
  
  myChart.setOption(option);
  
  // 添加窗口调整大小事件监听
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 数据异常波动洞察相关状态
const anomalyInsights = ref([
  {
    id: 1,
    title: '急诊科就诊量异常增长',
    description: '过去三天急诊科就诊量同比增长73%，明显高于季节性预期。',
    severity: 'high',
    date: '2023-07-15',
    department: '急诊科',
    metrics: ['患者数量'],
    trend: '↑ 73%',
    analysis: 'AI分析显示可能与近期体育赛事和暑期开始有关，建议增加急诊医护人员配置。'
  },
  {
    id: 2,
    title: '儿科药品库存异常消耗',
    description: '儿科感冒类药品消耗速度过去一周上升53%，库存可能在5天内耗尽。',
    severity: 'medium',
    date: '2023-07-14',
    department: '儿科',
    metrics: ['药品消耗'],
    trend: '↑ 53%',
    analysis: 'AI分析显示与季节性儿童呼吸道感染高发有关，建议及时补充库存。'
  },
  {
    id: 3,
    title: '内科B区患者满意度下降',
    description: '内科B区患者满意度评分从92分下降至78分，降幅达15.2%。',
    severity: 'medium',
    date: '2023-07-13',
    department: '内科',
    metrics: ['患者满意度'],
    trend: '↓ 15.2%',
    analysis: 'AI分析显示主要不满因素为等待时间过长和医生解释不充分，建议优化门诊流程。'
  },
  {
    id: 4,
    title: '超声科预约率异常下降',
    description: '超声科预约率从85%降至62%，但临时就诊率上升了27%。',
    severity: 'low',
    date: '2023-07-12',
    department: '超声科',
    metrics: ['预约率', '临时就诊率'],
    trend: '↓ 23% / ↑ 27%',
    analysis: 'AI分析显示可能与预约系统近期更新有关，部分患者无法成功在线预约，建议检查系统并进行用户测试。'
  }
]);

// 智能数据解读示例
const dataInterpretations = ref([
  {
    id: 1,
    title: '六月门诊量与收入分析',
    date: '2023-07-10',
    summary: '六月门诊总量比五月增长12.5%，但收入仅增长7.2%，低于预期。',
    insights: [
      'AI分析显示，增长主要来自常规检查类低价值服务',
      '专科高价值诊疗服务比例下降3.2%',
      '药品收入占比从32%降至28.5%',
      '医保报销比例上升，自费比例下降'
    ],
    recommendations: [
      '增强专科医生的预约可得性',
      '优化高价值诊疗服务的患者体验',
      '评估药品定价策略',
      '开发更多针对自费患者的增值服务'
    ]
  },
  {
    id: 2,
    title: '医护人员工作效率分析',
    date: '2023-07-08',
    summary: '医护人员平均每患者服务时间从18分钟缩短至15.5分钟，效率提升13.9%。',
    insights: [
      'AI分析显示，新电子病历系统减少了50%的文档时间',
      '医护协作流程优化减少了交接时间',
      '但患者报告的医生沟通满意度下降5.3%',
      '护士工作负荷分布不均，差异达到28%'
    ],
    recommendations: [
      '为医生提供沟通技巧培训',
      '评估是否需要增加医患沟通时间',
      '优化护士排班和任务分配',
      '继续改进电子病历系统的用户体验'
    ]
  }
]);

// 根据严重程度获取对应的样式类
const getSeverityClass = (severity) => {
  switch (severity) {
    case 'high': return 'severity-high';
    case 'medium': return 'severity-medium';
    case 'low': return 'severity-low';
    default: return '';
  }
};

// 模拟生成新的AI解读
const isGeneratingInsight = ref(false);
const generateNewInsight = () => {
  isGeneratingInsight.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    const newInsight = {
      id: dataInterpretations.value.length + 1,
      title: '医生工作负荷与服务质量相关性分析',
      date: '2023-07-16',
      summary: 'AI对10,000+患者记录和医生工作时数的分析显示，当医生日均接诊超过22人时，医疗质量指标出现显著下降。',
      insights: [
        '医生日均接诊量与医疗事故率呈正相关(r=0.68)',
        '接诊量超过22人/日时，患者满意度平均下降18.5%',
        '诊断准确率在高负荷时段下降7.3%',
        '医生自报疲劳指数与接诊量呈指数关系'
      ],
      recommendations: [
        '重新评估医生最佳接诊量标准',
        '在高峰期增加医生轮换或支持人员',
        '实施智能排班系统，平衡工作负荷',
        '为高负荷科室增加辅助诊断AI工具支持'
      ]
    };
    
    dataInterpretations.value.unshift(newInsight);
    isGeneratingInsight.value = false;
  }, 2000);
};
</script>

<template>
  <div class="ai-analytics-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">AI 智能数据分析</h1>
      <p class="page-subtitle">利用人工智能技术解读数据，发现隐藏的业务洞察</p>
    </div>
    
    <!-- 自然语言搜索区域 -->
    <div class="search-section">
      <div class="search-container">
        <div class="search-input-wrapper">
          <el-input
            v-model="searchQuery"
            placeholder="使用自然语言提问，例如：'找出上个月销售额最高的产品'"
            :suffix-icon="'Search'"
            @keyup.enter="performSearch"
            class="nl-search-input"
            clearable
          />
          <el-button type="primary" @click="performSearch" :loading="isSearching" class="search-button">
            {{ isSearching ? '搜索中...' : '搜索' }}
          </el-button>
        </div>
        
        <div class="search-history" v-if="searchHistory.length > 0">
          <span class="history-label">历史搜索:</span>
          <div class="history-tags">
            <el-tag
              v-for="(item, index) in searchHistory"
              :key="index"
              class="history-tag"
              @click="useHistorySearch(item)"
              size="small"
            >
              {{ item }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 搜索结果区域 -->
    <div class="search-results" v-if="Object.keys(searchResults).length > 0">
      <div class="result-header">
        <h2>{{ searchResults.title }}</h2>
        <el-button size="small" @click="clearSearch" type="text">
          <el-icon><Close /></el-icon>
          关闭
        </el-button>
      </div>
      
      <div class="chart-container" v-if="searchResults.chart">
        <div id="resultChart" class="result-chart"></div>
      </div>
      
      <div class="insight-container">
        <h3><el-icon><Lightbulb /></el-icon> AI 智能解读</h3>
        <p>{{ searchResults.insight }}</p>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 异常波动洞察 -->
      <div class="anomaly-section">
        <div class="section-header">
          <h2><el-icon><Warning /></el-icon> 数据异常波动洞察</h2>
          <p class="section-description">AI 持续监控业务数据并自动检测异常波动</p>
        </div>
        
        <div class="anomaly-list">
          <el-card
            v-for="anomaly in anomalyInsights"
            :key="anomaly.id"
            class="anomaly-card"
            :class="getSeverityClass(anomaly.severity)"
          >
            <div class="anomaly-header">
              <div>
                <span class="anomaly-severity" :class="getSeverityClass(anomaly.severity)">
                  {{ anomaly.severity === 'high' ? '高' : anomaly.severity === 'medium' ? '中' : '低' }}
                </span>
                <span class="anomaly-department">{{ anomaly.department }}</span>
              </div>
              <span class="anomaly-date">{{ anomaly.date }}</span>
            </div>
            
            <h3 class="anomaly-title">{{ anomaly.title }}</h3>
            <p class="anomaly-description">{{ anomaly.description }}</p>
            
            <div class="anomaly-metrics">
              <div v-for="(metric, idx) in anomaly.metrics" :key="idx" class="anomaly-metric">
                {{ metric }}
              </div>
              <div class="anomaly-trend">{{ anomaly.trend }}</div>
            </div>
            
            <div class="anomaly-analysis">
              <h4>AI 分析</h4>
              <p>{{ anomaly.analysis }}</p>
            </div>
          </el-card>
        </div>
      </div>
      
      <!-- 智能数据解读 -->
      <div class="interpretation-section">
        <div class="section-header">
          <h2><el-icon><DataAnalysis /></el-icon> AI 智能数据解读</h2>
          <div class="section-actions">
            <el-button type="primary" @click="generateNewInsight" :loading="isGeneratingInsight">
              {{ isGeneratingInsight ? '生成中...' : '生成新解读' }}
            </el-button>
          </div>
        </div>
        
        <div class="interpretation-list">
          <el-card
            v-for="interpretation in dataInterpretations"
            :key="interpretation.id"
            class="interpretation-card"
          >
            <div class="interpretation-header">
              <h3>{{ interpretation.title }}</h3>
              <span class="interpretation-date">{{ interpretation.date }}</span>
            </div>
            
            <div class="interpretation-summary">
              <p>{{ interpretation.summary }}</p>
            </div>
            
            <div class="interpretation-details">
              <div class="interpretation-section">
                <h4><el-icon><Lightbulb /></el-icon> 关键洞察</h4>
                <ul>
                  <li v-for="(insight, idx) in interpretation.insights" :key="idx">
                    {{ insight }}
                  </li>
                </ul>
              </div>
              
              <div class="interpretation-section">
                <h4><el-icon><Guide /></el-icon> AI 建议</h4>
                <ul>
                  <li v-for="(recommendation, idx) in interpretation.recommendations" :key="idx">
                    {{ recommendation }}
                  </li>
                </ul>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.ai-analytics-container {
  padding: 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
}

.page-subtitle {
  margin: 0 0 16px 0;
  color: var(--text-secondary);
}

.search-section {
  margin-bottom: 24px;
  background-color: var(--background-light);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-input-wrapper {
  display: flex;
  gap: 12px;
}

.nl-search-input {
  flex: 1;
}

.search-history {
  margin-top: 12px;
  display: flex;
  align-items: center;
}

.history-label {
  font-size: 13px;
  color: var(--text-secondary);
  margin-right: 8px;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  cursor: pointer;
}

.search-results {
  background-color: var(--background-light);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.chart-container {
  margin-bottom: 20px;
}

.result-chart {
  height: 400px;
  width: 100%;
}

.insight-container {
  background-color: rgba(var(--primary-color-rgb), 0.05);
  border-left: 4px solid var(--primary-color);
  padding: 16px;
  border-radius: 4px;
}

.insight-container h3 {
  margin-top: 0;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: var(--primary-color);
}

.insight-container p {
  margin: 0;
  line-height: 1.6;
}

.main-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-description {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: var(--text-secondary);
}

.anomaly-list, .interpretation-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.anomaly-card, .interpretation-card {
  height: 100%;
  transition: transform 0.2s;
}

.anomaly-card:hover, .interpretation-card:hover {
  transform: translateY(-5px);
}

.anomaly-header, .interpretation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.anomaly-severity {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  margin-right: 8px;
}

.severity-high {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  border-left: 3px solid #f56c6c;
}

.severity-high .anomaly-severity {
  background-color: #f56c6c;
  color: white;
}

.severity-medium {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
  border-left: 3px solid #e6a23c;
}

.severity-medium .anomaly-severity {
  background-color: #e6a23c;
  color: white;
}

.severity-low {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border-left: 3px solid #67c23a;
}

.severity-low .anomaly-severity {
  background-color: #67c23a;
  color: white;
}

.anomaly-department {
  font-size: 13px;
  color: var(--text-secondary);
}

.anomaly-date, .interpretation-date {
  font-size: 13px;
  color: var(--text-secondary);
}

.anomaly-title, .interpretation-header h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.anomaly-description, .interpretation-summary p {
  margin: 0 0 12px 0;
  font-size: 14px;
  line-height: 1.5;
  color: var(--text-primary);
}

.anomaly-metrics {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.anomaly-metric {
  background-color: rgba(var(--primary-color-rgb), 0.1);
  color: var(--primary-color);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.anomaly-trend {
  font-weight: 600;
  font-size: 14px;
}

.anomaly-analysis, .interpretation-section {
  background-color: rgba(0, 0, 0, 0.02);
  padding: 12px;
  border-radius: 4px;
  margin-top: 12px;
}

.anomaly-analysis h4, .interpretation-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
}

.anomaly-analysis p {
  margin: 0;
  font-size: 13px;
  line-height: 1.5;
}

.interpretation-summary {
  margin-bottom: 16px;
}

.interpretation-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.interpretation-section ul {
  margin: 0;
  padding-left: 20px;
}

.interpretation-section li {
  margin-bottom: 6px;
  font-size: 13px;
  line-height: 1.5;
}

.interpretation-section li:last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .anomaly-list, .interpretation-list {
    grid-template-columns: 1fr;
  }
  
  .search-input-wrapper {
    flex-direction: column;
  }
}
</style> 